<?php

namespace App\Http\Controllers\Api;

use App\Enums\OrderPay;
use App\Http\Controllers\Controller;
use App\Http\Requests\MaterialRequest;
use App\Models\Material;
use App\Models\Order;
use App\Services\OrderService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class MaterialController extends Controller
{

    public function download(MaterialRequest $request)
    {
        if (!$request->get('key')) {
            $user_id = auth('api')->user()->id ?? 0;
            if (!$user_id) {
                return failReturn('Login expired, please log in again', Response::HTTP_NOT_ACCEPTABLE);
            }
            $order = Order::query()->where('id', $request->get('order_id'))
                ->where('user_id', $user_id)
                ->where('pay', OrderPay::PAID)
                ->first();
            if (!$order) {
                return failReturn('数据异常');
            }
            //判断是否分配了资料给订单
            if (!$order->material_id) {
                //执行分配操作
                $order = app(OrderService::class)->allocationMaterial($order);
            }
            $material = $order->material;
            if (!$material) {
                return failReturn('资料不存在');
            }
            //这里返回下载链接
            $key = $user_id . Str::random(10);
            Cache::set($key, $material->id, now()->addMinutes(5));
            return successReturn([
                'download_url' => url('api/download') . '?key=' . $key,
            ]);
        } else {
            //这里做下载处理
            $key = $request->get('key', '');
            if (!$key) {
                die;
            }
            $material_id = Cache::get($key);
            if (!$material_id) {
                die;
            }
            $material = Material::query()->where('id', $material_id)->firstOrFail();
            Cache::forget($key);
            return Storage::disk('public')->download($material->path, $material->name);
        }

    }

}
